#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void wc_func(char *file,int ism,int isw,int isl);
int main(int argc ,char *argv[])
{
	int ism,isw,isl,opt;
	ism = isw = isl = 0;
	int count = 0;
	while((opt=getopt(argc,argv,"mwl"))!=-1)
	{
		count++;
		switch(opt)
		{
			case 'm':
				ism=1;
				break;
			case 'w':
				isw=1;
				break;
			case 'l':
				isl=1;
				break;
			case '?':
				printf("请查看该指令说明文档 %c\n",optopt);
				exit(0);
		}
	}	
	if(count==0)
	{
		ism=isw=isl=1;
	}
	if(optind==argc)
	{
		printf("wc error: have no file!\n");
	}
	for(;optind<argc;optind++)
	{
		wc_func(argv[optind],ism,isw,isl);
	}
	//printf("hello");
}

void wc_func(char *file,int ism,int isw,int isl)
{
	int t,m,w,l;
	int state = 0;
	FILE *in;
	if((in = fopen(file,"r"))==NULL)
	{
		printf("wc %s:no this file or dir\n",file);
		return;
	}
	w=m=l=0;
	while((t=fgetc(in))!=EOF)
	{
		/*if(t=='\t'||t==' ')
		{	
			w++;
		}
		else if(t=='\n')
		{
			l++;
		}*/
		
		if(t == '\n') {
            		l++;
            		state = 0;
            		continue;
        	} else if(t == ' ') {
            		state = 0;
            		continue;
        	} else if(t == '\r') {
            		state = 0;
            		continue;
        	} else {
            		if(state == 0) {
                	state = 1;
                	w++;
           		}
            		continue;
        	}
		m++;	
	}
	if(isl)
		printf("%-5d",l);
	if(isw)
		printf("%-5d",w);
	if(ism)
		printf("%-5d",m);
	printf("%-10s\n",file);
}







